package org.marsdonne.audits;

import com.fasterxml.jackson.databind.JsonNode;
import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.TypeDef;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import java.util.Date;

/**
 * （用户身份）认证授权（审计）域
 * 用于追溯用户身份的认证授权相关的专用过程
 */
@Entity
@Getter
@Setter
@EntityListeners(AuditingEntityListener.class)
@NoArgsConstructor
@TypeDef(typeClass = JsonBinaryType.class, defaultForType = JsonNode.class)
public class Auth extends LoggedEntity {
    @Column(nullable = false)
    private String username;

    @Column(nullable = false)
    private Identified.Action action;

    @Column(columnDefinition = "jsonb")
    private JsonNode additions;

    public Auth(String username, Identified.Action action, Date dateIdentified, JsonNode additions) {
        this.username = username;
        this.action = action;
        this.dateLogged = dateIdentified;
        this.additions = additions;
    }

    public Auth(Identified identified) {
        this(identified.getUser(), identified.getAction(), identified.getDateIdentified(), identified.getAdditions());
    }
}
